<template>
  <div class="permission">
    <div class="operate">
      <div>
        <div style="flex: 0 0 auto">
          <ep-search
            v-model="queryParam.b0102"
            placeholder="请输入点位名称"
            enter-button="chaxun "
            :size="size"
            @search="
              () => {
                this.listQuery();
              }
            "
          ></ep-search>
        </div>
        <ep-button
          :size="size"
          style="margin-left: 15px"
          icon="refresh.svg"
          @click="
            () => {
              this.flushPage();
            }
          "
        ></ep-button>
        <!--        <a-tree-select
            placeholder="请选择管理区域(可多选)"
            ref="taskArea"
            allowClear
            tree-checkable
            style="margin-left: 15px;width:22vw"
            v-model="queryParam.manageAreas"
            :show-checked-strategy="SHOW_PARENT"
            :treeData="taskAreaTree"
            @change="manageAreaChange()"
            :size="size"
        />-->

        <ep-button
          :size="size"
          style="margin-left: 15px"
          @click="
            () => {
              this.auditBatch('1');
            }
          "
          >批量通过</ep-button
        >-->
        <ep-button
          :size="size"
          style="margin-left: 15px"
          @click="
            () => {
              this.auditBatch('2');
            }
          "
          >批量驳回</ep-button
        >-->
        <ep-button
                  :size="size"
                  style="margin-left: 15px"
                  icon="export.svg"
                  @click="
                    () => {
                      this.exportExcel();
                    }
                  "
                  >导出</ep-button>
<!--        <zh-input   class="custom-input"  v-model="queryParam.d0703"    style="margin-left: 15px"  type="date"-->
<!--                  format="YYYY-MM" placeholder="请输入查询日期" ></zh-input>-->

<!--        <zh-input     class="custom-input2"   style="margin-left: 15px"   v-model="queryParam.d0404"  type="select"-->
<!--                     :options="dictData.d0404"  placeholder="选择巡查状态"    ></zh-input>-->
<!--        <ep-button-->
<!--            style="margin-left: 15px"-->
<!--            :size="size"-->
<!--            @click="-->
<!--            () => {-->
<!--              this.selectByMaterial();-->
<!--            }-->
<!--          ">搜索-->
<!--        </ep-button>-->
      </div>
    </div>

    <a-modal
      title="驳回"
      centered
      style=""
      width="35%"
      destroyOnClose
      :mask-closable="false"
      v-model="visible"
      @cancel="handleCancel"
    >
      <zh-form
        :span="24"
        ref="rejectForm"
        :model="rejectForm"
        labelAlign="right"
      >
        <zh-input
          prop="ad0403"
          type="textarea"
          placeholder="请输入驳回理由"
          :rows="4"
          v-model="rejectForm.ad0403"
        ></zh-input>
      </zh-form>
      <template slot="footer">
        <a-button @click="handleOk">保存</a-button>
        <a-button @click="handleCancel">关闭</a-button>
      </template>
    </a-modal>

    <div class="ep-table">
      <zh-table
        ref="tableList"
        size="medium"
        style="width: 100%"
        height="400px"
        :data="tableData"
        rowId="roleId"
        type="paging"
        :export-config="{}"
        :columns="tableColumn"
        @checkbox-change="selectChangeEvent"
        @checkbox-all="selectAllEvent"
        :url="tableUrl"
      >
        <template #filter="{ $panel, column }">
          <input
              type="type"
              v-for="(option, index) in column.filters"
              :key="index"
              v-model="option.data"
              @input="$panel.changeOption($event, true, option)"
          />
        </template>
        <template #operate="{ row }">
          <div class="alert-message">
            <i class="fa fa-exclamation-circle alert-message-icon"></i>
            <span class="alert-message-content" v-if="row.d0408==='未审核'?true:false" style="margin-right: 8px">
              <ep-button size="small" type="rank" @click="auditone(row)"
              >审核</ep-button
              >
            </span>
            <span class="alert-message-content" v-if="row.d0408==='审核通过'?false:true">
              <ep-button size="small" type="rank" @click="audit(row)"
                >驳回</ep-button
              >
            </span>
            <span class="alert-message-content" style="margin-left: 8px">
              <ep-button size="small" type="rank" @click="look(row)"
                >查看</ep-button
              >
            </span>
          </div>
        </template>
      </zh-table>
    </div>

    <a-modal
      :title="detailTitle"
      centered
      style=""
      width="90%"
      destroyOnClose
      :mask-closable="false"
      v-model="detailVisible"
      @cancel="detailVisible = false"
    > <patrol-child-detail ref="patrolChildDetail" />
      <template slot="footer">
        <ep-button @click="detailVisible = false">关闭</ep-button>
        <ep-button v-if="isaduit" @click="auditsig">审核</ep-button>
      </template>
    </a-modal>

<!--    <a-modal-->
<!--        title="条件搜索"-->
<!--        centered-->
<!--        style="top: 20px"-->
<!--        width="65%"-->
<!--        v-model="materialVisible"-->
<!--        cancelText="关闭"-->
<!--        okText="查询"-->
<!--        :mask-closable="false"-->
<!--        @ok="selectByMaterial"-->
<!--        @cancel="()=>{this.materialVisible = false}">-->
<!--      <div>-->
<!--        <zh-form ref="materialFormInfo" :model="materialFormInfo"  labelAlign="right" >-->
<!--          <zh-card style="width:100%">-->

<!--            <zh-row >-->
<!--              <zh-input :span="11" prop="d0703"    type="date"-->
<!--                       format="YYYY-MM" label="开始时间" v-model="materialFormInfo.d0703" :labelCol="{span:6}" :wrapperCol="{span:18}"></zh-input>-->
<!--              <zh-input :span="11" format="YYYY-MM" prop="d0704"  type="date" label="结束时间" v-model="materialFormInfo.d0704"  :labelCol="{span:6}" :wrapperCol="{span:18}"-->
<!--                        style="margin-left: 15px"></zh-input>-->
<!--            </zh-row >-->
<!--            <zh-row>-->
<!--              <zh-input style="float: left" prop="d0404" :span="22" type="select" :defaultFields='{label:"dictValue",value:"dictKey",}'-->
<!--                        :options="dictData.d0404"   label="巡查状态" v-model="materialFormInfo.d0404"-->
<!--                        :labelCol="{span:3}" :wrapperCol="{span:9}"  ></zh-input>-->
<!--            </zh-row>-->
<!--          </zh-card>-->
<!--        </zh-form>-->
<!--      </div>-->
<!--    </a-modal>-->

  </div>
</template>
<script>
import modal from "ant-design-vue/es/modal";
const SHOW_PARENT = TreeSelect.SHOW_PARENT;
import {
  getChildPatrolTaskList,
  getPermissionParams,
  patrolTaskAuditBatch,
} from "@/services/system/whdngxlApi";
import PatrolChildDetail from "@/pages/system/form/PatrolChildDetail";
import ZxChildDetail from "@/pages/system/form/ZxChildDetail";
import EpButton from "@/components/assembly/button";
import { TreeSelect } from "ant-design-vue";
import { mapGetters } from "vuex";
import {getBatchDict} from "@/services/system/api";
import commonExcelExport from '@/excel/commExcel'

export default {
  name: "PatrolChildTaskList",
  computed: {
    ...mapGetters(["size"]),
  },
  components: {
    PatrolChildDetail,
    ZxChildDetail,
    EpButton,
  },
  data() {
    return {
      dictData: {},
      filtersData: {},
      d0702:'',
      aduitxc:"",
      aduitsh:"",
      isaduit:false,
      queryParam: {
        b0102: "",
        d0703:"",
        d040:"",
        manageAreas: undefined,
      },
      taskAreaTree: [],
      materialVisible: false,
      materialFormInfo: {
        d0703: '',
        d0704: '',
        d0404:'',
        d0408:''
      },
      SHOW_PARENT,
      tableUrl: getChildPatrolTaskList,
      labelCol: {
        xs: { span: 24 },
        sm: { span: 8 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 },
      },
      // 分页参数
      tablePage: {
        total: 0,
        currentPage: 1,
        pageNum: 1,
        pageSize: 200,
      },
      tableColumn: [
        { type: "checkbox", width: 50, fixed: "left", visible: true, field: "checkbox", },
        {
          type: "seq",
          fixed: "left",
          align: "center",
          title: "序号",
          width: 60,
          visible: true,
        },
        {
          field: "d0401",
          title: "巡查任务ID",
          visible: false,
          align: "center",
        },
        {
          field: "b0101",
          title: "点位ID",
          visible: false,
          align: "center",
        },
        { field: "b0102", title: "巡查点位", align: "center",width: 150 ,visible: true },
        { field: "d0203", title: "巡查开始时间", align: "center", visible: true,width: 130,
          filters: [{ data: "" }],
          filterMethod: this.filterd0203Method,
          slots: {
            // 使用插槽模板渲染
            filter: "filter",
          }, },
        {
          field: "patrolTime",
          title: "巡查时间",
          sortable: true,
          align: "center",
          visible: true,
          width: 150
        },
        { field: "patrolMan", title: "巡查人", align: "center", visible: true ,width: 120
          ,
          filters: [{ data: "" }],
          filterMethod: this.filterpatrolManMethod,
          slots: {
            // 使用插槽模板渲染
            filter: "filter",
          }, },
        {
          field: "patrolResult",
          title: "巡查结果",
          align: "center",
          width: 120,
          visible: true,
        filters: []
  },
        {
          field: "d0408",
          title: "审核结果",
          align: "center",
          width: 120,
          visible: true,
          filters: []
        },
        {
          field: "operate",
          title: "操作",
          fixed: "right",
          align: "center",
          slots: {
            // 使用插槽模板渲染
            default: "operate",
          },
          visible: true,
        },
      ],
      tableData: [],
      //表头
      toolbarConfig: {
        custom: true,
        slots: {},
      },
      visible: false,
      selectedRowKeys: [] /*table选中keys*/,
      selectionRows: [] /*table选中records*/,
      d07Data: {},
      isct:true,
      iszx:false,
      rejectForm: { ad0403: "", ad0402: "" },
      auditList: [],
      detailTitle: "",
      detailVisible: false,
    };
  },
  mounted() {},
  created() {
    //获取任务范围
    this.$http.post(getPermissionParams, {}).then((res) => {
      const data = res.result;
      this.taskAreaTree = data.orgTreeData;
    });

    const params = {}
    params.dictFields = 'patrolResult,d0408'
    this.$http.post(getBatchDict, params).then(res => {
      this.dictData = res.result
      //获取筛选数据
      this.getFiltersData(this,'tableList')
    })

//     const param = {}
//     param.dictFields = 'd0404'
//     this.$http.post(getBatchDict, param).then(res => {
// debugger
//       this.dictData = res.result
//       res.result.d0404.push({
//         dictField : 'D0404',
//         dictKey: '99',
//         dictValue: '全部巡查状态'
//       })
//       console.log(res.result)
//       this.queryParam.d0404='99'
//     })
  },
  methods: {
    initData(data) {
      this.$nextTick(() => {
        if (data) {
          this.d07Data = data;
          if(data.d0706==='2'){
            this.iszx=true;
            this.isct=false;
          }
          this.listQuery();
          this.d0702=data.d0702;
        }
      });
    },
    manageAreaChange() {
      this.listQuery();
    },
    getFiltersData(that,tableName){
      //把拿到的字典遍历进筛选的数组中
      let keyArr = Object.keys(that.dictData)
      for(let i = 0;i<keyArr.length;i++){
        let filterKey = keyArr[i]
        let filterParam = that.dictData[filterKey]
        let filterObj = []
        for(let j = 0;j<filterParam.length;j++){
          let filterArr = {label:filterParam[j].dictValue,value:filterParam[j].dictValue}
          filterObj.push(filterArr)
        }
        that.filtersData[filterKey] = filterObj
        that.$refs[tableName].setFilter([filterKey]+'',that.filtersData[filterKey])
      }
    },
    filterd0203Method({ option, row }) {
      debugger
      this.queryParam.d0703=option.data
      return row.d0203.includes(option.data)
    },
    filterpatrolManMethod({ option, row }) {
      return row.patrolMan.includes(option.data)
    },
       exportExcel() {
         // const params = {};
         // params.d0701 = this.d07Data.d0701;
         // if (this.queryParam.d0703 != "" || this.queryParam.d0703 != null) {
         //   params.d0703 = this.queryParam.d0703.replaceAll('-','');
         // }
         // if (this.materialFormInfo.d0704 != "" || this.materialFormInfo.d0704 != null) {
         //   params.d0704 = this.materialFormInfo.d0704.replaceAll('-','');
         // }
         // if (this.queryParam.d0404 != "" || this.queryParam.d0404 != null) {
         //
         //   if(this.queryParam.d0404 !='99'){
         //     params.d0404 = this.queryParam.d0404;
         //   }
         // }
         this.$refs.tableList.exportData( this.d0702+'清单','csv');
        },
    openMaterialModal(){
      this.materialVisible = true
    },
    selectByMaterial(){
      debugger
      const params = {};
      params.d0701 = this.d07Data.d0701;
      if (this.queryParam.d0703 != "" || this.queryParam.d0703 != null) {
        params.d0703 = this.queryParam.d0703.replaceAll('-','');
      }
      // if (this.materialFormInfo.d0704 != "" || this.materialFormInfo.d0704 != null) {
      //   params.d0704 = this.materialFormInfo.d0704.replaceAll('-','');
      // }
      if (this.queryParam.d0404 != "" || this.queryParam.d0404 != null) {
        if(this.queryParam.d0404 !='99'){
          params.d0404 = this.queryParam.d0404;
        }
      }
      this.$refs.tableList.query(params);
      this.materialVisible = false
    },
    flushPage() {
      this.queryParam.b0102 = "";
      this.listQuery();
    },
    listQuery() {
      if (this.d07Data.d0701 == "" || this.d07Data.d0701 == null) {
        modal.warn({ title: "提示", content: "巡查任务总表ID不能为空" });
        return;
      }
      const params = {};
      if (this.queryParam.d0703 != "" || this.queryParam.d0703 != null) {
        params.d0703 = this.queryParam.d0703.replaceAll('-','');
      }
      if (this.queryParam.d0404 != "" || this.queryParam.d0404 != null) {
        if(this.queryParam.d0404 !='99') {
          params.d0404 = this.queryParam.d0404;
        }
      }
      params.d0701 = this.d07Data.d0701;
        params.b0102 = this.queryParam.b0102
      /*params.manageAreas = this.queryParam.manageAreas*/
      this.$refs.tableList.query(params);
    },
    //单个审核，只能是驳回
    audit(row) {
      this.auditList = [];
      this.auditList.push(row);
      this.showOrHide();
    },

    auditone(row) {
      if(row.patrolResult==='未巡查'){
        modal.warn({ title: "提示", content:  row.b0102+"未巡查无法审核！"});
        return;
      }
      this.auditList = [];
      this.auditList.push(row);
      this.rejectForm.ad0402 = "1";
      const params = {};
      params.auditList = this.auditList;
      params.ad0402 = this.rejectForm.ad0402;
      setTimeout(() => {
        this.$http
            .post(patrolTaskAuditBatch, params)
            .then((res) => {
              this.$message.info("审核成功！");
              this.handleCancel();
              this.listQuery();
            })
            .catch((error) => {});
      }, 50);
    },
    auditsig() {
      this.rejectForm.ad0402 = "1";
      const params = {};
      params.auditList = this.auditList;
      params.ad0402 = this.rejectForm.ad0402;
      setTimeout(() => {
        this.$http
            .post(patrolTaskAuditBatch, params)
            .then((res) => {
              this.$message.info("审核成功！");
              this.detailVisible = false;
              this.isaduit=false;
              this.handleCancel();
              this.listQuery();
            })
            .catch((error) => {});
      }, 50);
    },

    //批量审核
    auditBatch(type) {
      if (this.$refs.tableList.isAllChecked) {
        this.selectionRows = this.$refs.tableList.getCheckboxRecords();
      } else {
        this.selectionRows = this.$refs.tableList.getAllCheckboxRecords();
      }
      if (this.selectionRows.length === 0) {
        modal.warn({ title: "提示", content: "请至少选择一条数据" });
        return;
      }
      this.auditList = this.selectionRows;
      if (type == "1") {
        this.rejectForm.ad0402 = "1";
        const params = {};
        params.auditList = this.auditList;
        params.ad0402 = this.rejectForm.ad0402;
        setTimeout(() => {
          this.$http
            .post(patrolTaskAuditBatch, params)
            .then((res) => {
              this.$message.info("审核成功！");
              this.handleCancel();
              this.listQuery();
            })
            .catch((error) => {});
        }, 50);
      } else {
        this.rejectForm.ad0402 = "2";
        this.showOrHide();
      }
    },
    handleOk() {
      this.rejectForm.ad0402 = "2";
      const params = {};
      params.auditList = this.auditList;
      params.ad0402 = this.rejectForm.ad0402;
      params.ad0403 = this.rejectForm.ad0403;
      setTimeout(() => {
        this.$http
          .post(patrolTaskAuditBatch, params)
          .then((res) => {
            this.$message.info("审核成功！");
            this.handleCancel();
            this.listQuery();
          })
          .catch((error) => {});
      }, 50);
    },
    handleCancel() {
      this.visible = false;
    },
    showOrHide() {
      this.visible = !this.visible;
    },
    columnChange() {
      this.$refs.tableList.refreshColumn();
    },
    //复选框事件(保留翻页选中的数据)
    selectChangeEvent({ checked, records, reserves, row }) {
      // console.log(checked ? '勾选事件' : '取消事件')
      // console.log('当前选中的数据：' + records)
      // console.log('翻页时其他页的数据：' + reserves)
      // console.log('当前选中的数据行：' + row )
      //勾选选中时
      if (checked) {
        //第一次选数据，还未进行翻页时
        if (reserves.length == 0) {
          this.selectedRowKeys = records.map((v) => v.aac147);
          this.selectionRows = records;
        } else {
          //aac147集合，翻页存在已选中的数据时,拼接新选中的数据
          this.selectedRowKeys = [
            ...reserves.map((v) => v.aac147),
            ...records.map((v) => v.aac147),
          ];
          //数据集合，翻页存在已选中的数据时,拼接新选中的数据
          this.selectionRows = [...reserves, ...records];
        }
      } else {
        //取消选中时
        let aac147Index = this.selectedRowKeys.indexOf(row.aac147);
        if (aac147Index > -1) {
          //删除取消选中删除指定元素aac147
          this.$delete(this.selectedRowKeys, aac147Index);
        }

        let dataIndex = null;
        for (let i = 0; i < this.selectionRows.length; i++) {
          if (this.selectionRows[i].aac147 == row.aac147) {
            dataIndex = i;
            break;
          }
        }
        //删除取消选中的元素整个对象
        this.$delete(this.selectionRows, dataIndex);
      }
    },
    //vxe复选框当前页全选中方法(保留翻页选中的数据)：
    selectAllEvent({ checked, records, reserves }) {
      // console.log(checked ? '勾选事件' : '取消事件')
      // console.log('当前选中的数据：' + records)
      // console.log('翻页时其他页的数据：' + reserves)
      //全选中时
      if (checked) {
        //第一次选数据，还未进行翻页时
        if (reserves.length == 0) {
          this.selectedRowKeys = records.map((v) => v.aac147);
          this.selectionRows = records;
        } else {
          //aac147集合，翻页存在已选中的数据时,拼接新选中的数据
          this.selectedRowKeys = [
            ...reserves.map((v) => v.aac147),
            ...records.map((v) => v.aac147),
          ];
          //数据集合，翻页存在已选中的数据时,拼接新选中的数据
          this.selectionRows = [...reserves, ...records];
        }
      } else {
        //取消全选时,直接将翻页数据赋值，当前页数据不用加上
        this.selectionRows = reserves;
        this.selectedRowKeys = reserves.map((v) => v.aac147);
      }
    },
    look(row) {
      this.detailTitle = `${row.b0102}巡查详情`;
      this.detailVisible = true;
      this.aduitxc=row.patrolResult;
      this.aduitsh=row.d0408;
      debugger
      if(row.patrolResult==="已巡查"&&row.d0408==="未审核"){
        this.isaduit=true;
      }
      this.auditList = [];
      this.auditList.push(row);
      this.$nextTick(() => {
        this.$refs.patrolChildDetail.initData(row);
      });


    },
  },
};
</script>

<style lang="less" scoped>
.custom-input {
  width: 150px; /* 设置宽度 */
  height: 35px; /* 设置高度 */
}
.custom-input2 {
  width: 120px; /* 设置宽度 */
  height: 35px; /* 设置高度 */
}
.permission {
  //padding: 15px 20px 0;

  .desc,
  .operate {
    display: flex;
    align-items: center;
    justify-content: space-between;
    color: #fff;

    > div {
      flex: 0 0 auto;
      display: flex;
      align-items: center;
    }
  }

  .desc {
    margin-bottom: 20px;
  }

  .operate {
    margin-bottom: 15px;
    .field {
      flex: 0 0 auto;
      position: relative;
      margin-left: 15px;
      .field-box {
        position: absolute;
        top: 40px;
        left: 0;
        right: -40px;
        z-index: 99;
        border: 1px solid #2175a9;
        background: #002a44;
        border-radius: 5px;
        ul {
          padding: 10px;
          li {
            padding: 1px 0;
          }
        }
        .btn {
          display: flex;
          align-items: center;
          justify-content: space-between;
          padding: 5px;
          border-top: 1px solid #2175a9;
          color: #fff;
          p {
            flex: 1;
            text-align: center;
            cursor: pointer;
            &:hover {
              color: #49bbeb;
            }
          }
        }
      }
    }
  }
}
</style>
